# import threading
import requests
import io
from PIL import Image
import time
import os


def capture_frames(
    source: str,
    cookies: dict,
):
    """从指定源捕获视频帧并定时保存到本地"""
    cookie = cookies.get("auth_token")
    # 处理HTTP/HTTPS图像源
    if str(source).startswith("http"):
        response = requests.get(source,
                                stream=True,
                                timeout=10,
                                verify=False,
                                cookies={"auth_token": cookie})

        if response.status_code == 200:
            # 处理MJPEG流
            if 'multipart' in response.headers.get(
                    'Content-Type', '') or 'mjpeg' in response.headers.get(
                        'Content-Type', ''):
                bytes_data = bytes()
                for chunk in response.iter_content(chunk_size=1024):
                    # 检查是否需要停止
                    bytes_data += chunk
                    a = bytes_data.find(b'\xff\xd8')  # JPEG开始
                    b = bytes_data.find(b'\xff\xd9')  # JPEG结束
                    if a != -1 and b != -1:
                        jpg = bytes_data[a:b + 2]
                        bytes_data = bytes_data[b + 2:]
                        try:
                            img = Image.open(io.BytesIO(jpg))
                        except Exception as e:
                            print(f"处理帧时出错: {e}")
                        # 检查图片大小并压缩
                        img_byte_arr = io.BytesIO()
                        img.save(img_byte_arr, format='JPEG')
                        img_size = img_byte_arr.tell()
                        if img_size > 200 * 1024:  # 大于200KB进行压缩
                            # 计算压缩比例
                            quality = int((200 * 1024 / img_size) * 100)
                            if quality < 30:
                                quality = 30  # 保证最低质量
                            img.save("test.jpg", "JPEG", quality=quality)
                        else:
                            img.save("test.jpg")


def login(base_url, num):
    """模拟登录操作"""
    # 这里可以添加登录逻辑
    # url = "https://100.109.226.25/api/auth/login"
    print(f"{base_url}线程启动")
    session = requests.Session()
    payload = {"user": "admin", "passwd": "admin"}
    while 1:
        try:
            response = session.post(f'https://{base_url}/api/auth/login',
                                    data=payload,
                                    verify=False,
                                    timeout=10)
            if response.status_code == 200:
                print(response.text)
                # print("登录成功，获取cookie:", session.cookies.get_dict())
                # return session.cookies.get_dict()
                response = session.get(f'https://{base_url}/streamer/stream',
                                       stream=True,
                                       timeout=10,
                                       verify=False)
                if 'multipart' in response.headers.get(
                        'Content-Type', '') or 'mjpeg' in response.headers.get(
                            'Content-Type', ''):
                    bytes_data = bytes()
                    for chunk in response.iter_content(chunk_size=1024):
                        # 检查是否需要停止
                        bytes_data += chunk
                        a = bytes_data.find(b'\xff\xd8')  # JPEG开始
                        b = bytes_data.find(b'\xff\xd9')  # JPEG结束
                        if a != -1 and b != -1:
                            jpg = bytes_data[a:b + 2]
                            bytes_data = bytes_data[b + 2:]
                            try:
                                img = Image.open(io.BytesIO(jpg))
                            except Exception as e:
                                print(f"处理帧时出错: {e}")
                            # 检查图片大小并压缩
                            img_byte_arr = io.BytesIO()
                            img.save(img_byte_arr, format='JPEG')
                            img_size = img_byte_arr.tell()
                            if num == 1:
                                # 裁剪图片
                                img = img.crop((80, 150, 1850, 900))
                            if img_size > 200 * 1024:  # 大于200KB进行压缩
                                # 计算压缩比例
                                quality = int((200 * 1024 / img_size) * 100)
                                if quality < 30:
                                    quality = 30  # 保证最低质量
                                img.save(f"data/onecloud/temp_{num}.jpg",
                                         "JPEG",
                                         quality=quality)
                            else:
                                img.save(f"data/onecloud/temp_{num}.jpg")
                            time.sleep(1)  # 每秒保存一帧
            else:
                print("登录失败")
        except Exception as e:
            print(f"登录请求异常: {e}")


if __name__ == "__main__":
    from mqttser import mqtt_run
    from threading import Thread
    Thread(target=mqtt_run, args=('玩客云', [("software", 0)]),
           daemon=True).start()
    th_list = []
    ip_list = [
        "100.99.208.45",  #视频
        "100.109.226.25",  #报表
        "100.77.241.84",  #水草
        "100.66.110.109",  #机器人
        # "100.109.111.25",  #错误测试
    ]
    for index, ip in enumerate(ip_list):
        th = Thread(target=login, args=(ip, index), daemon=True)
        th_list.append(th)
    for th in th_list:
        th.start()
    for th in th_list:
        th.join()
